package com.example.demo1.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.demo1.domain.User;
import com.example.demo1.utils.ServerUtils;

public class UserService {
	public boolean login(String name, String password) {

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("name", name));
		params.add(new BasicNameValuePair("password", password));
		JSONObject jsonObject  = ServerUtils.invoke("/login", params);
		try {
			return jsonObject.getBoolean("success");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return false;

	}

	public List<User> getUserList(int max, int offset) {
		List<User> list = new ArrayList<User>();
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("max", max + ""));
		params.add(new BasicNameValuePair("offset", offset + ""));
		JSONObject result = ServerUtils.invoke("/user/userAction_list", params);
		try {
			JSONArray jsonArray =  result.getJSONArray("result");
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				User user = new User();
				user.setId(jsonObject.getString("id"));
				user.setName(jsonObject.getString("name"));
				user.setEmail(jsonObject.getString("email"));
				user.setBirth(jsonObject.getString("birth"));
				user.setPassword(jsonObject.getString("password"));
				user.setPic(jsonObject.getString("pic"));
				user.setSex(jsonObject.getBoolean("sex"));
				list.add(user);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		System.out.println(result);
		return list;
	}
}
